package com.test.threadlocal;

/**
 * @author ：biws
 * @date ：Created in 2020/12/18 16:29
 * @description：线程不安全案例
 */
public class ThreadA extends Thread {
    private int i;
    private UnsafeThread unsafeThread;

    ThreadA(int i, UnsafeThread unsafeThread) {
        this.i = i;
        this.unsafeThread = unsafeThread;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        unsafeThread.calc();

        System.out.println("i:" + i + ",count:" + unsafeThread.getCount());
    }
}

 class UnsafeThread {

    private int count = 0;

    public void calc() {
        count++;
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        UnsafeThread testThread = new UnsafeThread();
        for (int i = 0; i < 20; i++) {
            new ThreadA(i, testThread).start();
        }

        Thread.sleep(200);
        System.out.println("realCount:" + testThread.getCount());
    }
}
